package com.kason.security;

import com.kason.entity.User;
import com.kason.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

/**
 * 自定义权限认真实现
 * Created by IBM on 2018/6/30.
 */
public class AuthProvider implements AuthenticationProvider{

    @Autowired
    private IUserService iUserService;

    // 因为密码是md5加密过的， 所以此处需要一个md5类解密
    private final Md5PasswordEncoder passwordEncoder = new Md5PasswordEncoder();
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String userName = authentication.getName();
        String inputPassword = (String)authentication.getCredentials();
        // 从数据库中读取User
        User user = iUserService.findUserByName(userName);
        if (null == user) {
            throw new AuthenticationCredentialsNotFoundException("auth error");
        }
        if (this.passwordEncoder.isPasswordValid(user.getPassword(),inputPassword, user.getId())) {
            return new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
        } else {
            throw new BadCredentialsException("authError password not");
        }

    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
